package com.backend.system.service.processors.menu;


import cn.hutool.core.bean.BeanUtil;
import com.backend.system.beans.menu.MenuAddOrUpdateReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 新增或修改菜单处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.MENU_ADD_OR_UPDATE)
public class MenuAddOrUpdateProcessor extends AbstractProcessorTemplate<MenuAddOrUpdateReq, Boolean> {

    private Menu menu;

    @Override
    protected void init(ProcessorContext<MenuAddOrUpdateReq> context) {
        MenuAddOrUpdateReq req = context.getData();
        menu = null;

        // 如果是修改菜单
        boolean isAddMenu = Objects.isNull(req.getId());
        if (!isAddMenu) {
            menu = menuService.getById(req.getId());
            if (Objects.isNull(menu)) {
                throw CustomException.argsError("菜单不存在");
            }
        } else {
            menu = new Menu();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<MenuAddOrUpdateReq> context) {
        MenuAddOrUpdateReq req = context.getData();
        BeanUtil.copyProperties(req, menu);
        return menuService.saveOrUpdate(menu);
    }
}
